package com.itheima.dianming.template;

import com.baidu.aip.face.AipFace;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;

@Component
@EnableConfigurationProperties(BaiduAIProperties.class)
public class BaiduAITemplate {

    @Autowired
    private BaiduAIProperties baiduAIProperties;


    private AipFace client ;

    @PostConstruct
    public void init(){
        client =  new AipFace(baiduAIProperties.getAppId(),
                baiduAIProperties.getApiKey(),
                baiduAIProperties.getSecretKey());
    }

    public boolean detectFace(String image){
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 传入可选参数调用接口
        HashMap<String, Object> options = new HashMap<String, Object>();
        options.put("face_field", "age");
        options.put("max_face_num", "2");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");
        // 调用接口
        String imageType = "BASE64";
        // 人脸检测
        // 人脸检测
        JSONObject res = client.detect(image, imageType, options);
        Object msg = res.get("error_msg");
        if("SUCCESS".equals(msg)){
            return true;
        }
        return false;
    }

    public boolean detectFaceOnUrl(String imageUrl){
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 传入可选参数调用接口
        HashMap<String, Object> options = new HashMap<String, Object>();
        options.put("face_field", "age");
        options.put("max_face_num", "2");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");
        // 调用接口
        String imageType = "URL";
        // 人脸检测
        JSONObject res = client.detect(imageUrl, imageType, options);
        Object msg = res.get("error_msg");
        if("SUCCESS".equals(msg)){
            return true;
        }
        return false;
    }
}
